package com.qf.qfcenterdata.listeners;

import com.alibaba.fastjson.JSON;
import com.qf.common.constant.KafkaConstant;
import com.qf.common.feigns.DeviceApi;
import com.qf.common.model.DeviceCmd;
import com.qf.qfcenterdata.service.MongoService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class DeviceCmdListener {

    @Autowired
    private DeviceApi deviceApi;

    @Autowired
    private MongoService mongoService;

    @KafkaListener(topics = {KafkaConstant.DEVICE_CMD_TOPIC},groupId = KafkaConstant.DEVICE_CMD_GROUP)
    public void dataLis(ConsumerRecord record){
        String value = (String) record.value();
        System.out.println("===" + value);

        //缺少tenantId&productKey
        DeviceCmd deviceCmd = JSON.parseObject(value, DeviceCmd.class);
        //查询租户id
        String tenantId = deviceApi.getTenantIdByDeviceKey(deviceCmd.getDeviceKey());
        deviceCmd.setTenantId(tenantId);
        //查询产品的key
        String productKey = deviceApi.getProductKeyByDeviceKey(deviceCmd.getDeviceKey());
        deviceCmd.setProductKey(productKey);

        deviceCmd.setCreateTime(new Date());

        //保存指令数据到mongodb
        mongoService.saveDeviceCmd(deviceCmd);

    }
}
